import { baseApiUrl, path } from "../../utils/config";
import { login, index, news, standCalendar, videoOpen } from '../../utils/api';
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
Page({
  data: {
    baseImageUrl: baseApiUrl,
    rotation: [],

    page: 1,
    last_page: 1,
    list: [],

    sheet_show: false,
    is_open: 0
  },
  onShow() {
    videoOpen().then(res => {
      let is_open = res.is_open;
      this.setData({ is_open });
    });

    let token = app.globalData?.token ?? "";
    if (token) {
      this.getIndex();
      this.getList();
      this.getHome();
      return false;
    }
    wx.login({
      success: async (res) => {
        let code = res.code;
        if (!code) return false;

        login({ code }).then(async (res) => {
          let { id } = res.data;
          app.globalData.user_id = id;
          wx.setStorageSync('user_id', id);

          const token = res.token;
          app.globalData.token = token;
          wx.setStorageSync('token', token);

          this.getIndex();
          this.getList();
          this.getHome();
        })
      }
    });
  },
  onReachBottom() {
    let page = this.data.page;
    let last_page = this.data.last_page;
    if (page == last_page) return false;
    page += 1;
    this.setData({ page });
    this.getList();
  },
  async getIndex() {
    let { rotation, haibao } = await index();
    app.globalData.poster = haibao;
    this.setData({ rotation });
  },
  async getHome() {
    let { calendar } = await standCalendar();
    let array = [];
    let obj = {};
    calendar.forEach(item => {
      let duration = item.duration;
      if (!duration) return false;
      let hour = parseInt(duration / 60 % 24);
      let mm = parseInt(duration % 60);
      mm = mm < 10 ? '0' + mm : mm;
      obj[item.day] = `${hour}时${mm}分`;
      array.push(item.day);
    });
    app.globalData.list = obj;
    app.globalData.defaultDate = array;
  },
  async getList() {
    let res = await news({
      page: this.data.page,
      limit: 10
    });
    res = res.news;
    let { data, last_page } = res;
    let list = this.data.page == 1 ? data : [...this.data.list, ...data];
    this.setData({ list, last_page })
  },
  navigate(e) {
    let { item } = e.currentTarget.dataset;
    let { news_id } = item;
    if (news_id <= 0) return;
    let url = `/pages/article/article?id=${news_id}`;
    wx.navigateTo({ url })
  },
  router(e) {
    let { url } = e.currentTarget.dataset;
    url ? wx.navigateTo({ url }) : Toast('敬请期待');
  },
  router_shopping() {
    let is_open = this.data.is_open;
    is_open ? wx.navigateTo({ url: "/pages/shopping/shopping" }) : Toast('敬请期待');
  },
  onShareAppMessage() {
    let poster = app.globalData.poster;
    return {
      path,
      imageUrl: poster
    }
  },
  onShareTimeline() { }
})
